// 主界面
;define(function(require, exports, module) {
    'use strict';
    var util = require("util");
    var base = require("base");
    var router = require("../hash/pageRouter");
    var dialog = require("dialog");
    var validate = require("validate");
    var databind = require("databind");
    var js_deliveryNoticeDetail = require("./deliveryNoticeDetail.js");
    var css_deliveryDetail = require("./deliveryDetail.css");
    var pageIndex = 1,
        pageSize = 10,
        totalPageCount = 1,
        totalRecordCount = 0; //分页初始化
    var imgSrc;
    var noticeState;
    var left;
    var inventoryId;
    var deliveryNoticeId;
    var deliveryId ;
    var deliveryDetail;
    var init = function(page){
    	deliveryNoticeId = page.params.deliveryNoticeId || base.getUrlParam("deliveryNoticeId");
		deliveryId  = page.params.deliveryId ||base.getUrlParam("deliveryId");
		noticeState = page.params.noticeState || base.getUrlParam("noticeState");
		left = base.getUrlParam("left");
		if (left == null) {
			left = 1;
		}
		inquireDeliveryDetail();
		initEvent();
		router.init();
		
		$("#leftMenu1").find(".leftMenu-item").removeClass("leftMenu-active");
		$("#leftMenu1 #newTaskList").parent(".leftMenu-item").addClass("leftMenu-active");
    };
	var initEvent = function(){
		//若未登录，则返回登陆页面
		if(base.getData("sid")==null||base.getData("sid")==""||base.getData("sid")==undefined){
			top.location.href="../login/login.html";
		}
		
		//点击放货通知
		$(".deliveryNoticeList").unbind("click").click(function() {
			top.location.href = "../deliveryNotice/deliveryNoticeList.html?noticeState=" + noticeState + "&left=" + left;
		});
		
		//点击放货配送
//		$(".deliveryList").unbind("click").click(function() {
//			router.route("deliveryNotice/deliveryList.html?deliveryNoticeId=" + deliveryNoticeId + "&noticeState=" + noticeState, true);
//		});
		
		//点击签收详情
		$(".signDelivery_detail").unbind("click").click(function(){
			var abnormalType = $(this).attr("id");
			var inventoryId = [];
        	var $this = $(this).parents("tr.tr_style");
			inventoryId.push($this.attr("inventoryId"));
			var containerInventorys;
			$.each(deliveryDetail.datas[0].containerInventorys,function(i,val){
		   	if(val.inventoryId==inventoryId){
		   		containerInventorys = val;
		   	}
		   });
			if(abnormalType==2){//异常签收
				dialog.showDialog($("#abnormalSignDelivery_dialog"));
				databind.fillForm($("#abnormalSignDelivery_dialog"),containerInventorys);
				showImg($(".signAbnormalFile").parent().find(".showImg"),containerInventorys.signAbnormalFile);
				showImg($(".signSoundRecorde").parent().find(".showImg"),containerInventorys.signSoundRecorde);
				showImg($(".signPreFile").parent().find(".showImg"),containerInventorys.signPreFile);
				showImg($(".signSuffixFile").parent().find(".showImg"),containerInventorys.signSuffixFile);
				$(".uploadFilepreTallyP").remove();
				$(".closeLayer").remove();
				$(".footerBtnContract").remove();
			}else{
				dialog.showDialog($("#signDelivery_dialog"));
				databind.fillForm($("#signDelivery_dialog"),containerInventorys);
				showImg($(".signPreFile").parent().find(".showImg"),containerInventorys.signPreFile);
				showImg($(".signSuffixFile").parent().find(".showImg"),containerInventorys.signSuffixFile);
				$(".uploadFilepreTallyP").remove();
				$(".footerBtnContract").remove();
				$(".closeLayer").remove();
				databind.disableInput($("#signDelivery_dialog"));
			}
		});
		
//		$("#deliveryDetail").on("click", ".deliveryDetailException", function(){
//			router.route("exception/exceptionDetailInfo.html?deliveryDetail=1&inventoryId=" + $(this).parents("tr").attr("inventoryId"));
//		});
		
		//异常签收
		$(".abnormalSignDelivery").unbind("click").click(function(){
			var inventoryId = [];
           var $this = $(this).parents("tr.tr_style");
		   inventoryId.push($this.attr("inventoryId"));
			dialog.showDialog($("#abnormalSignDelivery_dialog"));
			databind.fillForm($("#abnormalSignDelivery_dialog"),{inventoryId:inventoryId});
			
			var iti = $(this).parents("tr").attr("inventoryId");
			
			$("#sure_abnormalSignDelivery").unbind("click").click(function(){
				databind.submitDom($(".abnormalSignDeliveryContent"),function(){
					base.alert(1,"异常签收成功");
					dialog.hideDialog($("#abnormalSignDelivery_dialog"));
					router.route("exception/exceptionDetailInfo.html?deliveryDetail=1&inventoryId=" + iti);
//					router.route("deliveryNotice/deliveryDetail.html?deliveryId=" + deliveryId+"&noticeState="+noticeState, true);
				});
			});
		uploadFileAbnormalEven();
		});
		
		//点击接受放货任务
		$("#acceptTasks").on("click",function(){
			dialog.showConfirmDialog("接受放货任务","是否要接受此放货任务？",function(){
				
					base.fnAjax({
			action : "confirmDeliveryNotice.json",
			oData : {
				deliveryNoticeId:deliveryNoticeId
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					base.alert(1, "接受放货任务成功");
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
			});
		});
		
		//正常签收
		$(".signDelivery").unbind("click").click(function(){
			var inventoryId = [];
           var $this = $(this).parents("tr.tr_style");
		   inventoryId.push($this.attr("inventoryId"));
			dialog.showDialog($("#signDelivery_dialog"));
			databind.fillForm($("#signDelivery_dialog"),{inventoryId:inventoryId});
			
			$("#sure_signDelivery").unbind("click").click(function(){
				databind.submitDom($(".signDeliveryContent"),function(){
					base.alert(1,"签收成功");
					dialog.hideDialog($("#signDelivery_dialog"));
					router.route("deliveryNotice/deliveryDetail.html?deliveryId=" + deliveryId+"&noticeState="+noticeState, true);
				});
			});
	uploadFileEven();
		});
    };
    
    var uploadFileAbnormalEven = function(){
    	$("#abnormalSignDelivery_dialog").on("change","#uploadSignSoundRecorde",function(){
			uploadFile($(this).parent().parent().attr("id"),$(this).attr("id"));
			
		});
			//上传异常图片
			$("#abnormalSignDelivery_dialog").on("change","#uploadSignAbnormalFile",function(){
			uploadFile($(this).parent().parent().attr("id"),$(this).attr("id"));
			
		});
		
			//上传签收前照片
		$("#abnormalSignDelivery_dialog").on("change","#uploadSignPreFile1",function(){
			uploadFile($(this).parent().parent().attr("id"),$(this).attr("id"));
			
		});
		//上传签收后照片
		$("#abnormalSignDelivery_dialog").on("change","#uploadSignSuffixFile1",function(){
			uploadFile($(this).parent().parent().attr("id"),$(this).attr("id"));
		});
		//删除图片
		$("#abnormalSignDelivery_dialog").on("click",".closeLayer",function(){
			$(this).parent().parent().find(".file").css("display","inline-block");
			$(this).parent().remove();
			savefilesUuid($(this).parent().parent());
		});
    }
    
    //上传文件相关事件绑定
    var uploadFileEven = function(){
			
			//上传签收前照片
		$("#signDelivery_dialog").on("change","#uploadSignPreFile",function(){
			uploadFile($(this).parent().parent().attr("id"),$(this).attr("id"));
			
		});
		//上传签收后照片
		$("#signDelivery_dialog").on("change","#uploadSignSuffixFile",function(){
			uploadFile($(this).parent().parent().attr("id"),$(this).attr("id"));
		});
		//删除图片
		$("#signDelivery_dialog").on("click",".closeLayer",function(){
			$(this).parent().parent().find(".file").css("display","inline-block");
			$(this).parent().remove();
			savefilesUuid($(this).parent().parent());
		});
    }
    //获取放货配送明细(配送信息)
    var inquireDeliveryDetail = function(){
    	base.fnAjax({
			action: "inquireDeliveryDetail.json",
			async: false,
			oData: {
				deliveryId: deliveryId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					deliveryDetail = data;
					var deliveryDetailTpl = $("#deliveryDetailTpl").html();
					var html = juicer(deliveryDetailTpl, data);
                $(".deliveryDetail_main_content").html(html);
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
    }
     //显示图片
    var showImg = function(dom,fileUuid){
    	var fileUuids = fileUuid.split(",");
    	var html = "";
    	var imgSrc = "";
    	for(var i=0;i<fileUuids.length;i++){
    		imgSrc = fileUuids[i];
    		if(imgSrc.length!=0){
    			 html = "<label class=\"finance-file\"><img  src=\"/finance/api/1.0/downloadFile.file?fileUuid="+imgSrc+"\" class=\"finance-field-img\"  alt=\""+imgSrc+"\"  /> <a class=\"closeLayer\" ></a></label>";
              $(dom).html(html);
    		}
             
    	}
    }
   
   var uploadFile1 = function(domId,id){//指定p标签的dom的ID,img的id
    	 if ($("#"+id).val() != "") {
            
            $.ajaxFileUpload({
                url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
                secureuri: false,
                fileElementId: id,
                dataType: 'json',
                success: function(data) {
	        		imgSrc = data.data[0].fileUuid;
					html = "<label class=\"finance-file\"><img  src=\"../../../res/png/voice_icon.png\" class=\"finance-field-img\"  alt=\""+imgSrc+"\"  /> <a  class=\"closeLayer\" ></a></label>";
	                $("#"+domId).append(html);
	                savefilesUuid($("#"+domId));
	                if($("#"+domId).find(".finance-field-img").length==1){
	                	$("#"+domId).find(".file").css("display","none");
	                }
                },
                complete: function(xml) {
                },
                error: function(data, status, e) {
                	if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
                }
            });
        } else {
            base.alert(3, "请选择文件！");
        }
         
    }
   
   var uploadFile = function(domId,id){//指定p标签的dom的ID,img的id
    	 if ($("#"+id).val() != "") {
            var fileType = "jpg,png,bmp";
            var prompt  = validate.validateFileType($("#"+domId).find("#"+id),fileType);
            if(prompt.length > 1){
                base.alert(2,prompt);
                return;
            }
            $.ajaxFileUpload({
                url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
                secureuri: false,
                fileElementId: id,
                dataType: 'json',
                success: function(data) {
	        		imgSrc = data.data[0].fileUuid;
	        		var html = "<label class=\"finance-file\"><img  src=\"/finance/api/1.0/downloadFile.file?fileUuid="+imgSrc+"\" class=\"finance-field-img\"  alt=\""+imgSrc+"\"  /> <a class=\"closeLayer\" ></a></label>";
	                $("#"+domId).append(html);
	                savefilesUuid($("#"+domId));
	                if($("#"+domId).find(".finance-field-img").length==1){
	                	$("#"+domId).find(".file").css("display","none");
	                }
                },
                complete: function(xml) {
                },
                error: function(data, status, e) {
                	if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
                }
            });
        } else {
            base.alert(3, "请选择文件！");
        }
         
    }
   
   //更新fileUuuid保存字段
    var savefilesUuid = function(dom){
    		var filesUuids = "";
    	var imgDom =dom.find(".finance-field-img");
    	  var number = imgDom.length;
                 $.each(imgDom,function(i,object){
                 	if(i==number-1){
                 		filesUuids += object.alt;
                 	}else{
                 		filesUuids += object.alt+",";
                 	}
                 
                 });
              dom.parent().find(".signPreFile").val(filesUuids);
              dom.parent().find(".signSuffixFile").val(filesUuids);
               dom.parent().find(".signSoundRecorde").val(filesUuids);
              dom.parent().find(".signAbnormalFile").val(filesUuids);
    }
    return {
        init:init
    };
});